﻿using System.Linq;
using Behaviorize.CodeGenerator.CodeModel;
using EnvDTE;
using EnvDTE80;

namespace Behaviorize.CodeGenerator.CodeGenerating
{
	internal static class AttributesGenerator
	{
		internal static void SetClassAndAttributes(CodeClass2 testClass, Feature feature)
		{
			SetTestAttribute(testClass);
			SetFeatureDescriptionAttribute(testClass, feature);
			SetUserStoryAttribute(testClass, feature);
		}

		private static void SetUserStoryAttribute(CodeClass2 testClass, Feature feature)
		{
			CodeAttribute attr = testClass.Attributes.OfType<CodeAttribute>().SingleOrDefault(a => a.Name == "UserStory");

			if (feature.Story == null && attr != null)
			{
				attr.Value = string.Empty;
				return;
			}

			if (attr == null)
			{
				attr = testClass.AddAttribute("UserStory", null);
			}

			attr.Value = string.Format("AsA = \"{0}\", IWant = \"{1}\", SoThat = \"{2}\"", feature.Story.Role, feature.Story.Goal, feature.Story.Motivation);
		}

		private static void SetFeatureDescriptionAttribute(CodeClass2 testClass, Feature feature)
		{
			CodeAttribute attr = testClass.Attributes.OfType<CodeAttribute>().SingleOrDefault(a => a.Name == "FeatureDescription");

			if (feature.Description == null && attr != null)
			{
				attr.Value = string.Empty;
				return;
			}

			if (attr == null)
			{
				attr = testClass.AddAttribute("FeatureDescription", null);
			}

			attr.Value = "\"" + feature.Description + "\"";
		}

		private static void SetTestAttribute(CodeClass testClass)
		{
			bool testAttributePresent = testClass.Attributes.Cast<CodeAttribute>()
				.Any(attribute => attribute.Name == "TestClass" || attribute.Name == "TestFixture");

			if (!testAttributePresent)
				testClass.AddAttribute("TestClass", null);
		}	 
	}
}